package controllers;

import helpers.CacheHelper;
import helpers.IdUniqueHelper;
import helpers.UrlHelper;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import models.DirectoryModel;
import models.DomainModel;

import debugs.DomainDebug;

import services.CrawlerDomain;
import systems.Recently;

import entities.Domain;

public class DomainInfoServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		
		String path = ((HttpServletRequest) request).getRequestURI();
		String name = URLDecoder.decode(path.toLowerCase().replaceAll(request.getServletPath() + "/", ""),"UTF-8");
		String update = (String) request.getParameter("update");
		
		if (name == null || name.isEmpty() || !UrlHelper.checkDomain(name)) {
			response.sendRedirect("/msg/page-not-found");
			return;
		}
		
		DomainModel domainModel = DomainModel.getInstance();
		Domain domain = domainModel.get(name);
		
		if (domain == null 
				|| (domain != null && update != null && domain.getAuthKey().equalsIgnoreCase(update))) 
		{
			domain = new Domain();
			domain.setDomain(name);
			
			domain = CrawlerDomain.getInfo(domain);
			
			if (!domain.getRating().isEmpty()) {
				domain.setUpdated(new Date());
				domain.setAuthKey(IdUniqueHelper.getId());
				domainModel.insert(domain);
				
				//Update recently update
				Recently.insert(name, "updated");
				
				//Update directory
				DirectoryModel directoryModel = DirectoryModel.getInstance();
				directoryModel.insert(domain.getDomain());
				
			} else {
				/*response.sendRedirect("/msg/page-not-found");
				return;*/
			}
			System.out.println("Get Updadte Domain");
		} else {
			System.out.println("Get Cached Data");
		}
		
		Recently.insert(name, "recently");
		
		//Cache header
		response.addHeader("Cache-Control", "public, max-age=60000");
		
		request.setAttribute("domain", domain);
		try {
			request.getRequestDispatcher("/pages/info.jsp").forward(request, response);
		} catch (ServletException e) {
			e.printStackTrace();
		}
	}
}
